package cn.bird.storm.component.sensitive;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public  class SensitiveJsonSerializer extends JsonSerializer<Object> {

    private final JsonSerializer<Object> serializer;

    public SensitiveJsonSerializer(JsonSerializer<Object> serializer) {
        this.serializer = serializer;
    }

    @Override
    public void serialize(Object object, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        if (object instanceof String str) {
            if (StrUtil.isNotBlank(str)) {
                object = processSensitiveField(str);
            }
        }
        if (this.serializer == null) {
            serializerProvider.defaultSerializeValue(object, jsonGenerator);
        } else {
            this.serializer.serialize(object, jsonGenerator, serializerProvider);
        }
    }

    /**
     * 对于输入进行脱敏处理
     * @param input 需要处理的字段
     * @return 脱敏后的字段
     */
    private static String processSensitiveField(String input) {
        if (StrUtil.isBlank(input)) {
            return input;
        }
        input = StrUtil.trim(input);
        int strLen = input.length();
        if(strLen >= 15){
            input = DesensitizedUtil.idCardNum(input, 6, 3);
        }else if(strLen >= 11) {
            input = DesensitizedUtil.fixedPhone(input);
        }else{
            input = DesensitizedUtil.password(input);
        }
        return input;
    }
}